package match

import (
	"sanguo/node/common/orderMap"
	"sanguo/node/node_team/com"
	"time"
)

type Queue struct {
	BattleLevelType int32
	Level           int32
	Size            int32
	queue           *orderMap.OrderMap
}

func NewQueue(_type, level int32) *Queue {
	return &Queue{
		BattleLevelType: _type,
		Level:           level,
		Size:            0,
		queue:           orderMap.NewOrderMap(),
	}
}

func (this *Queue) GetQueueOjb(nodeId uint64) *Object {
	obj := this.queue.GetValueByKey(nodeId)
	if obj == nil {
		return nil
	} else {
		return obj.(*Object)
	}
}

func (this *Queue) AddQueue(nodeId uint64, o *Object) {
	this.queue.Add(nodeId, o)
	this.Size++
}

func (this *Queue) DelQueue(nodeId uint64) {
	this.queue.Del(nodeId)
	this.Size--
}

func (this *Queue) ClearQueue() {
	this.Size = 0
	this.queue = orderMap.NewOrderMap()
}

//匹配
func (this *Queue) TryMatch(now time.Time) {
	if this.queue.Len() == 0 {
		return
	}

	objs := []*Object{}
	teamObjs := []*Object{}
	noTeamObjs := []*Object{}
	size := int32(0)

	for i := 0; i < this.queue.Len() && (len(teamObjs) < 1 || len(noTeamObjs) < com.MatchRoleCount); i++ {
		obj := this.queue.GetValueByIdx(i).(*Object)
		if obj.TeamID == 0 {
			if len(noTeamObjs) < com.MatchRoleCount {
				noTeamObjs = append(noTeamObjs, obj)
			}
		} else {
			if len(teamObjs) < 1 {
				teamObjs = append(teamObjs, obj)
			}
		}
	}

	matchOK := false

	if len(teamObjs) >= 1 { //一个队伍+单人
		objs = append(objs, teamObjs[0])
		size += teamObjs[0].Size

		if int32(len(noTeamObjs))+size >= com.MatchRoleCount {
			for _, obj := range noTeamObjs {
				objs = append(objs, obj)
				size++
				this.DelQueue(obj.NodeID)
				if size >= com.MatchRoleCount {
					matchOK = true
					break
				}
			}
		} else {
			//加机器人
		}
	} else { //全是单人
		if len(noTeamObjs) >= com.MatchRoleCount {
			for _, obj := range noTeamObjs {
				objs = append(objs, obj)
				size++
				this.DelQueue(obj.NodeID)
				if size >= com.MatchRoleCount {
					matchOK = true
					break
				}
			}

		}
	}

	if matchOK {
		CreatRoom(objs)
	} else {

	}
}
